import { _decorator, Color, Component, Event, Graphics, view, game, BlockInputEvents } from 'cc';
import { EventManager } from '../../RunTime/EventManager';
import { EVENT_ENUM, CTRL_ENUM } from '../../Enum';
const { ccclass, property } = _decorator;

const SCREEN_WIDTH = view.getVisibleSize().width
const SCREEN_HEIGHT = view.getVisibleSize().height

enum FadeStatus {
    IDLE,
    IN,
    OUT
}

@ccclass('DrawManager')
export class DrawManager extends Component {
    beginTime: number = 0
    ctx: Graphics
    duration: number
    fadeResolve: (value?: PromiseLike<null>) => void
    fadeStatus: FadeStatus = FadeStatus.IDLE
    block: BlockInputEvents

    init(){
        this.block = this.addComponent(BlockInputEvents)
        this.ctx = this.addComponent(Graphics)
        this.setAlpha(1)
    }

    protected update(dt: number): void {
        const percent = (game.totalTime - this.beginTime) / this.duration
        if (this.fadeStatus == FadeStatus.IN){
            if (percent >= 1){
                this.fadeStatus = FadeStatus.IDLE
                this.setAlpha(1)
                this.fadeResolve()
            } else {
                this.setAlpha(percent)
            }
        }

        if (this.fadeStatus == FadeStatus.OUT){
            if (percent >= 1){
                this.fadeStatus = FadeStatus.IDLE
                this.setAlpha(0)
                this.fadeResolve()
            } else {
                this.setAlpha(1-percent)
            }
        }

    }

    private setAlpha(percent: number) {
        this.ctx.clear()
        this.ctx.rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
        this.ctx.fillColor = new Color(0, 0, 0, 255 * percent)
        this.ctx.fill()
        this.block.enabled = percent === 1
    }

    fadeIn(duration: number = 200){
        this.setAlpha(0)
        this.duration = duration
        this.fadeStatus = FadeStatus.IN
        this.beginTime = game.totalTime
        return new Promise(resolve => {
            this.fadeResolve = resolve
        })
    }
    fadeOut(duration: number = 200){
        this.setAlpha(1)
        this.duration = duration
        this.fadeStatus = FadeStatus.OUT
        this.beginTime = game.totalTime
        return new Promise(resolve => {
            this.fadeResolve = resolve
        })
    }

    mask(){
        this.setAlpha(1)
        this.fadeStatus = FadeStatus.IN
    }
    
}